package com.lingshi.shopping_file_service.service;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.lingshi.shopping.enums.ErrorEnums;
import com.lingshi.shopping.exception.BusException;
import com.lingshi.shopping.service.FileService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@DubboService
public class FileServiceImpl implements FileService {



    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;


    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.serverUrl}")
    private String serverUrl;

    public OSS ossClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }


    @Override
    public String uploadImage(byte[] fileBytes, String fileName) {
        OSS oss = ossClient();
        try {
            //上传的文件
            InputStream inputStream = new ByteArrayInputStream(fileBytes);

            //获取文件后缀
            String extName = FileNameUtil.extName(fileName);

            //生成新的随机文件名称
            fileName = RandomUtil.randomNumbers(20) + "." + extName;

            //上传文件
            PutObjectResult putObjectResult = oss.putObject(bucketName, fileName, inputStream);
            return serverUrl+"/"+fileName;
        } catch (Exception e) {
            throw new BusException(ErrorEnums.FILE_UPLOAD_ERROR);
        }finally {
            oss.shutdown();
        }
    }

    @Override
    public void delete(String filePath) {
        OSS oss = ossClient();
//        String filePath = "http://lingshi-oss-test.oss-cn-beijing.aliyuncs.com/52392813135310318417.jpeg";
        //截取文件名 52392813135310318417.jpeg
        String fineName = FileNameUtil.getName(filePath);
        try {
            oss.deleteObject(bucketName,fineName);
        }finally {
            oss.shutdown();
        }
    }
}
